<?php

/**
 * account actions.
 *
 * @package    sfwixet
 * @subpackage account
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class accountActions extends sfActions
{
 /**
  * Executes index action
  *
  * @param sfRequest $request A request object
  */
  public function executeIndex(sfWebRequest $request)
  {
    $this->forward('default', 'module');
  }
  
  public function executeUsernameExists(sfWebRequest $request){
  	if($request->getParameter("username")){
  		 $user = Doctrine::getTable("sfGuardUser")->findByUsername($request->getParameter("username"))->getFirst();
  		 $normal = "/^[a-z0-9_\+-0-9{5,128}][a-z0-9_\+-0-9{5,128}]*[a-z0-9_\+-0-9{5,128}]$/i";
  		 echo json_encode(is_object($user) || preg_match($normal, $request->getParameter("username"))==0);
  	}else echo json_encode(true);
  	return sfView::NONE;
  }
  public function executeValidateAccount(sfWebRequest $request){
		$languages = $this->getRequest()->getLanguages();
		$this->getUser()->setCulture($languages[0]);
  		$validation = Doctrine::getTable("AccountValidation")->findByHash($request->getParameter("hash"))->getFirst();
  		if($validation){
  			$username = strtolower(trim(str_replace(" ", "", $validation->getFirstname().".".$validation->getLastname())));
  			$exist = Doctrine::getTable("sfGuardUser")->findByUsername($username)->getFirst();
  			$i = 1;
  			while($exist){
  				$newUsername = $username."".$i;
  				$exist = Doctrine::getTable("sfGuardUser")->findByUsername($newUsername)->getFirst();
  				$i++;
  			}
  				
  			$this->error = false;
  			$this->firstname = $validation->getFirstname();
  			$this->lastname = $validation->getLastname();
  			$this->email = $validation->getEmail();
  			$this->hash = $validation->getHash();
  			$this->username = $i == 1?$username:$newUsername;
			//Get the country
			 $ch = curl_init();
		        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		        $url="http://api.wipmania.com/".$_SERVER['REMOTE_ADDR'];
		        curl_setopt($ch, CURLOPT_URL,$url);
		        $res = curl_exec ($ch);
		        
			$this->country = $res;
			//
  			
  		}
  		else
  			$this->error = true;
  }
  public function executePasswordRequest(sfWebRequest $request){
  	$i18n = sfContext::getInstance()->getI18n();
  	$this->getUser()->setCulture('es_ES');
  		try{
  			$user = Doctrine::getTable("sfGuardUser")->findByEmailAddress($request->getParameter("email","nobody"))->getFirst();
  			if(is_object($user)){
  				$destino = $user->getEmailAddress();
  				$asunto = "Recuperar datos Wixet";
  				
  				$request = new passwordRecovery();
				$request->setUserId($user->getId());
				try{
					$request->save();
				}catch (Exception $e){
					Doctrine::getTable("PasswordRecovery")->find($user->getId())->delete();	
				}
				$characters = array(
				"A","B","C","D","E","F","G","H","J","K","L","M",
				"N","P","Q","R","S","T","U","V","W","X","Y","Z",
				"1","2","3","4","5","6","7","8","9");
				$hash = "";
				for($i=0;$i<=20;$i++){
					$number = rand(0,32);
					$hash .= $characters[$number];
				}
				$hash = md5($hash);
				$request->setHash($hash);
				$request->save();
  		        $cuerpo="Tus identificadores son<br/>
  		        Email: ".$user->getEmailAddress()."<br/>
  		        Nombre de usuario: ".$user->getUsername()."<br/>
  		        <br/>
        		Para crear una nueva contraseña por favor accede al siguiente enlace<br/>
        		<a href='http://www.wixet.com/core/account/validatePasswordRequest/hash/".$hash."'>http://www.wixet.com/core/account/validatePasswordRequest/hash/".$hash."</a><br>
        		-----------------<br>
        		Un saludo, el equipo de Wixet";
  				
  				$ch = curl_init();
		        $url = "http://wixetmail.congdegnu.es/enviarMailValidacion.php";
		        curl_setopt($ch, CURLOPT_URL,$url);
		        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		        curl_setopt ($ch, CURLOPT_POST, 1);
		        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
		        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
		        curl_setopt ($ch, CURLOPT_POSTFIELDS, "destino=".$destino."&asunto=".$asunto."&cuerpo=".$cuerpo);
		        $res = json_decode(curl_exec ($ch));
				
		        if($res->error)
					throw new Exception($i18n->__("Email can not be sent"));
				else
					echo json_encode(array("error"=>false));
  			}else throw new Exception($i18n->__("This email does not exist in the database"));
  		}catch(Exception $e){
  				echo json_encode(array("error"=>true,"message"=>$e->getMessage()));
  		}
  		return sfView::NONE;
  }
  
  public function executeValidatePasswordRequest(sfWebRequest $request){
  	  	$validation = Doctrine::getTable("PasswordRecovery")->findByHash($request->getParameter("hash"))->getFirst();
  		if($validation){
  			$user = $validation->getUser();
  			$this->error = false;
  			$this->firstname = $user->getFirstname();
  			$this->lastname = $user->getLastname();
  			$this->email = $user->getEmailAddress();
  			$this->hash = $validation->getHash();
  			$this->username = $user->getUsername();
  		}
  		else
  			$this->error = true;
  }
  
  public function executeNewPassword(sfWebRequest $request){
  	$validation = Doctrine::getTable("PasswordRecovery")->findByHash($request->getParameter("hash"))->getFirst();
  	try{
  		if($validation){
  			$password = trim($request->getParameter("password"));
  			$user = $validation->getUser();
  		 	if(strlen($password) > 0){
  		 		$user->setPassword($password);
  		 		LdapLogin::updatePassword($user->getUsername(), $password);
  		 		$validation->delete();
  				echo json_encode(array("error"=>false)); 		
  			} else throw new Exception("Please write a password"); 	
  		} else throw new Exception("Invalid hash");
  	}catch(Exception $e){
  		echo json_encode(array("error"=>true,"message"=>$e->getMessage()));
  	}
  	return sfView::NONE;

  }
  
  public function executeSendVerification(sfWebRequest $request){
  	$i18n = sfContext::getInstance()->getI18n();
  	$this->getUser()->setCulture('es_ES');
  	
  	$email = trim($request->getParameter("email"));
  	$firstname = trim($request->getParameter("firstname"));
  	$lastname = trim($request->getParameter("lastname"));
  	
  	$message = "";
  	$normal = "/^[a-z0-9_\+-]+(\.[a-z0-9_\+-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*\.([a-z]{2,4})$/i";
 	if (!preg_match($normal, $email)) {
  		$message=$i18n->__("Invalid email address");
	}else if(strlen($firstname) == 0){
		$message=$i18n->__("Invalid firstname");
	}else if(strlen($lastname) == 0){
		$message=$i18n->__("Invalid lastname");
	}else{
		$users = Doctrine::getTable("sfGuardUser")->findByEmailAddress($email);
		if($users->count()>0)
			$message = $i18n->__("Email already exists. Please use other email");
	}
	
	
	if(strlen($message) == 0){
			
		
		$validation = new AccountValidation();
		$validation->setEmail($email);
		try{
			$validation->save();
		}catch (Exception $e){
			Doctrine::getTable("AccountValidation")->findByEmail($email)->getFirst()->delete();	
		}
		$characters = array(
		"A","B","C","D","E","F","G","H","J","K","L","M",
		"N","P","Q","R","S","T","U","V","W","X","Y","Z",
		"1","2","3","4","5","6","7","8","9");
		$hash = "";
		for($i=0;$i<=20;$i++){
			$number = rand(0,32);
			$hash .= $characters[$number];
		}
		$hash = md5($hash);
		$validation->setHash($hash);
		$validation->setFirstname($firstname);
		$validation->setLastname($lastname);
		$validation->save();
        $destino=$email;
        $asunto="Validacion de tu cuenta Wixet";
        $cuerpo="Gracias por registarte en Wixet<br/>
        Por favor haz accede al siguiente enlace:<br/>
        <a href='http://www.wixet.com/core/account/validateAccount/hash/".$hash."'>http://www.wixet.com/core/account/validateAccount/hash/".$hash."</a><br>
        -----------------<br>
        Un saludo, el equipo de Wixet";
        $ch = curl_init();
        $url = "http://wixetmail.congdegnu.es/enviarMailValidacion.php";
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt ($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt ($ch, CURLOPT_POSTFIELDS, "destino=".$destino."&asunto=".$asunto."&cuerpo=".$cuerpo);
        $res = json_decode(curl_exec ($ch));
		
        if($res->error)
			echo json_encode(array("error"=>true,$i18n->__("Email can not be sent")));
		else
			echo json_encode(array("error"=>false));
	}
	else
		echo json_encode(array("error"=>true,"message"=>$message));
	
	return sfView::NONE;
  	 
  }
  
  public function executeNewUser(sfWebRequest $request)
  { 
  	$validation = Doctrine::getTable("AccountValidation")->findByHash($request->getParameter("hash"))->getFirst();
  	try{
  		if($validation){
  			$username = $request->getParameter("username");
  			$firstname = $request->getParameter("firstname");
  			$lastname = $request->getParameter("lastname");
  			$password = $request->getParameter("password");
  			$birthday = $request->getParameter("date");
  			//Get the country
			$ch = curl_init();
	        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	        $url="http://api.wipmania.com/".$_SERVER['REMOTE_ADDR'];
	        curl_setopt($ch, CURLOPT_URL,$url);
	        $country = curl_exec ($ch);
			//
  			$user = Doctrine::getTable("sfGuardUser")->findByUsername($username)->getFirst();
  		 	if(!is_object($user)){
  		 		if($lastname && $firstname && $password)
  		 		{
  		 			$normal = "/^[0-9]{4}-[0-9]{1,2}-[0-9]{1,2}$/i";
  		 			if(preg_match($normal,$birthday)){
		  		 			exec('/'.sfConfig::get("sf_root_dir").'/symfony guard:create '.$validation->getEmail().' '.$username.' '.$password.' --firstname='.$firstname.' --lastname='.$lastname.' --birthday='.$birthday.' --country='.$country, $stdout, $error);
							if($error == 1)
						  		throw new Exception("User can not be created. Probably the username is wrong or your country is undefined");
						  	else{
						  		$validation->delete();
						  		echo json_encode(array("error"=>false));
					  		}
  		 			} else throw new Exception("Birthday is not valid, please use YYYY-MM-DD");
  		 		} else throw new Exception("Please provide a firstname, lastname and password");
  		 	} else throw new Exception("This username already exists");
  		} else throw new Exception("Invalid hash");
  	}catch(Exception $e){
  		echo json_encode(array("error"=>true,"message"=>$e->getMessage()));
  	}
  	return sfView::NONE;

  }
}
